<!-- 组织详情 -->
<script lang="ts" setup>
import { computed, ref, type PropType } from 'vue'
import type { IDbFormItem, IDbSelect } from '@/types/global'
import DuiForm from '@/common-ui/dui-form/index.vue'
import useNotic from '@/hooks/useNotic'
import * as orgApi from '@/api/org'
import type { IOrgData, IOrgInitData } from '../config/type'

const emits = defineEmits(['refresh'])

const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  disabled: {
    type: Boolean,
    default: false
  },
  types: {
    type: Array as PropType<IDbSelect[]>
  }
})

// 详情id
const infoId = ref('')
// 是否禁用组织类型选择
const typeDisabled = ref(false)
// 是否显示弹窗
const showDialog = ref(false)
const ruleFormRef = ref<InstanceType<typeof DuiForm>>()
// 表单配置
const formConfig = computed<IDbFormItem[]>(() => {
  return [
    { label: '上级组织', prop: 'parentName', type: 'text', span: 24 },
    { label: '组织名称', prop: 'orgName', type: 'input', required: true, span: 24 },
    { label: '排序', prop: 'sort', type: 'number', span: 12 },
    {
      label: '组织类型',
      prop: 'orgType',
      type: 'select',
      disabled: typeDisabled.value,
      list: props.types ?? [],
      required: true,
      span: 12
    }
  ]
})
// 表单数据
const defaultData: IOrgData = {
  parentName: '',
  parentId: '',
  orgName: '',
  sort: 0,
  orgType: ''
}
const formData = ref<IOrgData>(JSON.parse(JSON.stringify(defaultData)))

/**
 * 弹窗初始化
 */
function init(data: IOrgInitData, orgTypeDisabled: boolean = false) {
  infoId.value = data.id || ''
  typeDisabled.value = orgTypeDisabled

  const defaultForm = JSON.parse(JSON.stringify(defaultData as any))
  Object.keys(defaultForm).forEach((key) => {
    ;(formData.value as any)[key] = data[key] ?? defaultForm[key]
  })

  showDialog.value = true
}
/**
 * 点击提交
 */
function submitClick() {
  ruleFormRef.value
    ?.validate()
    .then(() => {
      // 添加
      let reqFunc = orgApi.addOrg
      let params: any = formData.value
      // 修改
      if (infoId.value) {
        reqFunc = orgApi.editOrg
        params = { ...formData.value, id: infoId.value }
      }
      reqFunc(params).then((res) => {
        if (res.success) {
          useNotic().success('提交成功！')
          showDialog.value = false
          emits('refresh')
        }
      })
    })
    .catch(() => {})
}

defineExpose({
  init
})
</script>

<template>
  <dui-dialog v-model="showDialog" :title="title">
    <dui-form ref="ruleFormRef" :form-config="formConfig" :form-data="formData" :disabled="disabled" />
    <template #footer>
      <el-button @click="showDialog = false">关闭</el-button>
      <el-button type="primary" @click="submitClick" v-if="!disabled"> 确定 </el-button>
    </template>
  </dui-dialog>
</template>
